package com.qf.config;

import com.qf.service.impl.UserDetailsService;
import com.qf.utils.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration //标识当前类是配置类，用于配置Spring容器的组件
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
//开启全局方法安全配置，prePostEnabled = true表示开启基于方法的权限控制，
// securedEnabled = true表示开启基于注解的权限控制
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    @Autowired
    private UserDetailsService userDetailsService;

    //重写AuthenticationManager的authenticationManagerBean方法,用于自定义认证规则
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    //重写configure方法，用于配置认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        // 传入自己的UserDetailService,实现根据数据库进行认证
        // passwordEncoder 指定密码比对方式,此次指定BCrypt 加密规则
        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }


    /**
     * 配置权限信息
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 允许匿名访问
                .antMatchers("/hello", "/world").anonymous()
                // 允许有指定权限访问
                .antMatchers("/add").hasAuthority("system:user:add")
                .antMatchers("/delete").hasAuthority("system:user:del")
                .antMatchers("/delete/all").hasAuthority("system:user:del")
                .antMatchers("/update").hasAuthority("system:user:edit")

                .antMatchers("/list").hasAuthority("system:user:list")
                 //只允许有这个角色访问
                .antMatchers("/get").hasRole("超级管理员")
                // 匿名访问,放行
                .antMatchers("/img/**", "/**/*.js", "/**/*.css").permitAll()
                .antMatchers("/register","/user/login").permitAll()
                // 其他所有资源,认证后(登录)访问
                .antMatchers("/**").authenticated();
//                .and().formLogin();  //禁用security自己的登录验证
        // 【重点】基于token，所以不需要session，即所以认证信息都存放在token中，不需要session
        http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        http.cors().and().csrf().disable();

        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
//        // 设置权限异常时的处理类
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);

        // 指定jwt解析拦截器
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }


}
